package org.dim.oa.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.dim.oa.dto.ModelDTO;
import org.dim.oa.mapper.FormProcessMapper;
import org.dim.oa.po.FormProcessEntity;
import org.dim.oa.po.ServerResponse;
import org.dim.oa.vo.ModelVo;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/model")
@Slf4j
public class ModelController {
    @Resource
    private RepositoryService repositoryService;

    @Autowired
    FormProcessMapper formProcessMapper;

    /**
     * 查询部署
     * @return
     */
    @RequestMapping("/list")
    public ServerResponse list(){
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();
        List<ModelDTO> records = list.stream()
                .map(
                        processDefinition -> {
                            InputStream xmlInputStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getResourceName());
                          //  InputStream pngInputStream = repositoryService.getProcessDiagram(processDefinition.getId());
                            String xmlStr="";
                            try {
                                xmlStr = IOUtils.toString(xmlInputStream,StandardCharsets.UTF_8);
                            }catch (Throwable e){
                                log.error("解析xml文件错误:{}",e);
                            }

                            return ModelDTO.builder()
                                    .xmlStr(xmlStr)
                                    .svgStr("")
                                    .deploymentId(processDefinition.getDeploymentId())
                                    .id(processDefinition.getId())
                                    .procId(processDefinition.getKey())
                                    .name(processDefinition.getName())
                                    .desc(processDefinition.getDescription())
                                    .build();
                        }).collect(Collectors.toList());

        return ServerResponse.success(records);
    }

    /**
     *
     * @return
     */
    @SneakyThrows
    @RequestMapping("/preview")
    public void preview(String a,HttpServletResponse ServerResponse){
        //需要根据act_re_procdef的ID_（表id去查，而非模板的key或name或文件资源名）
        InputStream processDiagram = repositoryService.getProcessDiagram(a);
        ServerResponse.setHeader("Content-type", "image/svg+xml;charset=UTF-8");
        ServerResponse.setHeader("Content-disposition", "inline;");
        ServerResponse.getOutputStream().write(IOUtils.toByteArray(processDiagram));
    }

    @SneakyThrows
    @PostMapping("/add")
    public ServerResponse addModel(@RequestBody ModelVo modelVo){
        //让请假永远请求最新的流程模板
        repositoryService.createDeployment()
                .addBytes(modelVo.getName() + ".bpmn20.xml", modelVo.getXmlStr().getBytes(StandardCharsets.UTF_8))
                .addBytes(modelVo.getName() + ".svg", modelVo.getSvgStr().getBytes(StandardCharsets.UTF_8))
                .name(modelVo.getName())
                .key(modelVo.getProcId())
                .deploy();
        QueryWrapper<FormProcessEntity> objectQueryWrapper = new QueryWrapper<>();
        FormProcessEntity byDictId = formProcessMapper.selectOne(objectQueryWrapper.eq("dict_id",modelVo.getProcessType()));
        FormProcessEntity build = FormProcessEntity.builder().dictId(modelVo.getProcessType())
                .pdfKey(modelVo.getProcId()).build();
        if (byDictId!=null){
            build.setId(byDictId.getId());
            formProcessMapper.updateById(build);
        }else {
            formProcessMapper.insert(build);
        }
        return ServerResponse.success("ok");
    }
}
